import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, compute, UserPageQuery, CreateCrudOptionsRet, CreateCrudOptionsProps, ScopeContext} from '@fast-crud/fast-crud';
import * as _ from 'lodash-es';
import * as api from './api';
import { request } from '/@/utils/service';
import { dictionary } from '/@/utils/dictionary';
import {inject} from "vue";


// 注释编号:django-vue3-admin__crud400716:这里账号的子表进来
import subTableComponent from "../DatabaseUserViewSet/SubDatabaeUserViewSet/index.vue";
import LinksubTableComponent from "../DatabaseLinkViewSet/SubDatabaseLinkViewSet/index.vue";

import { fa } from 'element-plus/es/locale';

// 注释编号:django-vue3-admin-crud355117:代码开始行
// 功能说明:导入多选批量删除需求
import XEUtils from 'xe-utils';
import { nextTick, ref } from 'vue';


//此处为crudOptions配置
export default function (object: CreateCrudOptionsProps): CreateCrudOptionsRet {
	
	const {crudRef } = object.crudExpose;
	const { crudExpose } = object;

	const pageRequest = async (query: any) => {
		return await api.GetList(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		if (row.id) {  
			form.id = row.id;
		}
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};

    const exportRequest = async (query: UserPageQuery) => {
		return await api.exportData(query)
	};

		// 注释编号:django-vue3-admin-crud402311:代码开始行
		// 功能说明:配置选中行的功能
		
		//记录选中的行
		const selectedRows = ref<any>([]);

		const onSelectionChange = (changed: any) => {
			const tableData = crudExpose.getTableData();
			const unChanged = tableData.filter((row: any) => !changed.includes(row));
			// 添加已选择的行
			XEUtils.arrayEach(changed, (item: any) => {
				const ids = XEUtils.pluck(selectedRows.value, 'id');
				if (!ids.includes(item.id)) {
					selectedRows.value = XEUtils.union(selectedRows.value, [item]);
				}
			});
			// 剔除未选择的行
			XEUtils.arrayEach(unChanged, (unItem: any) => {
				selectedRows.value = XEUtils.remove(selectedRows.value, (item: any) => item.id !== unItem.id);
			});
		};
		const toggleRowSelection = () => {
			// 多选后，回显默认勾选
			const tableRef = crudExpose.getBaseTableRef();
			const tableData = crudExpose.getTableData();
			const selected = XEUtils.filter(tableData, (item: any) => {
				const ids = XEUtils.pluck(selectedRows.value, 'id');
				return ids.includes(item.id);
			});
	
			nextTick(() => {
				XEUtils.arrayEach(selected, (item) => {
					tableRef.toggleRowSelection(item, true);
				});
			});
		};

		// 注释编号:django-vue3-admin-crud402311:代码结束行


	return {
		// 注释编号:django-vue3-admin-crud565217:代码开始行
		// 功能说明:这里要配置return，不然crudExpose获取不到
		selectedRows,
		toggleRowSelection,
		// 注释编号:django-vue3-admin-crud565217:代码结束行


		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			actionbar: {
				buttons: {
					export:{
                        click(){
                            return exportRequest(crudExpose.getSearchFormData())
                        }
					},
				}
			},
			form: {
				col: { span: 8 },
				// // labelWidth: '100px',
				wrapper: {
					is: 'el-dialog',
					width: '1200px',
				},
				group: {
					groups: {
						base: {
							slots: {
								label: () => { return (<span style={{ color: "blue" }}>基本信息</span>);}
							},
							columns: [ "host", "host_ip", "env", "name", "product", "status", "edition", "version", "release", "sid", "ipaddress", "port", "log_model", "role", "characterset", "encryption" ]
						},
						manage: {
							slots: {
								label: () => { return (<span style={{ color: "blue" }}>账号信息</span>);}
							},
							columns: [ "superuser", "superpwd", "online_form", "offline_form", "subTable" ]
						},
						linkserver: {
							slots: {
								label: () => { return (<span style={{ color: "blue" }}>LinkServer</span>);}
							},
							columns: [ "LinksubTable" ]
						},
					},
				},
			},
			viewForm: {
				wrapper: {
					buttons: {
						ok: { show: false },
						cancel: { show: false },
						reset: { show: false },
					},
				},
			},
			search: {
				container: {
					layout: "multi-line"
				},
				col: {
					span: 4
				},
				options: {
					// labelWidth: "100px"
				}
			},
			table: {
				rowKey: 'id', //设置你的主键id， 默认rowKey=id
				onSelectionChange,
				onRefreshed: () => toggleRowSelection(),   // 注释编号:django-vue3-admin-crud255417:需要配置toggleRowSelection
				// size: "small",
			},
			columns: {
				// 注释编号:django-vue3-admin-crud260511:代码开始行
				// 功能说明:要配置出来$checked
				$checked: {
					title: "选择",
					form: { show: false },
					column: {
						type: "selection",
						align: 'center',
						width: '40px',  // 注释编号:django-vue3-admin-crud340311:这个宽度你要按照自己的页面为调整，不然会出现一个display: inline-flex，导致无法居中显示
						columnSetDisabled: true, //禁止在列设置中选择
					}
				},
				// 注释编号:django-vue3-admin-crud260511:代码结束行
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '55px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				id: {
					title: 'ID',
					type: 'number',
					column: { show: false },
					search: { show: false },
					form: { show: false },
				},
				host: {
					title: '主机名',
					type: 'input',
					search: { show: true},
					column: {
						minWidth: 180,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: 'DB主机名必填' }],
						component: {},
					},
				},
				host_ip: {
					title: '主机IP',
					type: 'input',
					search: { show: true },
					column: {
						minWidth: 120,
						sortable: 'custom',
					},
					form: { 
						// helper: '请输入IP地址格式如192.168.1.1',
						rules: [{ pattern:/^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/, message: '格式如192.168.1.1或255.255.255.0'},
							{ required: true, message: '主机IP必填' }
						],
						component:{},
					},
				},
				name: {
					title: '实例名',
					type: 'input',
					search: { show: false },
					column: {
						minWidth: 120,
						sortable: 'custom',
					},
					form:{
						rules: [{ required: true, message: '数据库实例名必填' }],
						component:{},
					},
				},
				env: {
					title: 'Env.',
					type: 'dict-select',
					search: { 
						show: true, 
						component: {
							placeholder: ' ',
						}
					},
					dict: dict({
						data: [
							{ value: 'PRD', label: 'PRD' },
							{ value: 'STB', label: 'STB' },
							{ value: 'QAS', label: 'QAS' },
							{ value: 'DEV', label: 'DEV' },
						],
					}),
					column: { 
						minWidth: 80,
						sortable: 'custom',
					 },
					form:{
						rules: [{ required: true, message: 'Env.必填' },
							{ pattern:/^(PRD|STB|QAS|DEV)$/, message: '选择PRD/STB/QAS/DEV其中一个'}
						],
						component:{},
					},
				},
				product: {
					title: 'Product',
					type: 'dict-select',
					search: { 
						show: true, 
						component: {
							placeholder: ' ',
						}
					},
					dict: dict({
						data: [
							{ value: 'Oracle', label: 'Oracle' },
							{ value: 'PostgreSQL', label: 'PostgreSQL' },
							{ value: 'SQL Server', label: 'SQL Server' },
							{ value: 'MySQL', label: 'MySQL' },
							{ value: 'Others', label: 'Others' },
						],
					}),
					column: { 
						minWidth: 120,
						sortable: 'custom',
					 },
					 form:{
						rules: [{ required: true, message: 'Product必填' }],
						component:{},
					},
				},
				edition: {
					title: 'Edition',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				version: {
					title: 'Version',
					type:'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				release: {
					title: 'Release',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				sid: {
					title: '数据库',
					type: 'input',
					search: { show: true },
					column: { 
						minWidth: 160,
						sortable: 'custom',
					 },
					form:{
						rules: [{ required: true, message: '数据库必填' }],
						component:{},
					},
				},
				ipaddress: {
					title: 'DB IP',
					type: 'input',
					search: { show: true },
					column: { 
						minWidth: 120,
						sortable: 'custom', },
					form: { 
						// helper: '请输入IP地址格式如192.168.1.1',
						rules: [{ pattern:/^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/, message: '格式如192.168.1.1或255.255.255.0'},
							{ required: true, message: 'DB IP必填' },
						],
					},
				},
				port: {
					title: 'DB Port',
					type: 'number',
					search: { show: false },
					column: { 
						width: 110,
						sortable: 'custom',
					},
					form:{
						rules: [{ required: true, message: 'DB Port必填' }],
						component:{},
					},
				},
				log_model: {
					title: '归档日志',
					type: 'input',
					search: { show: false },
					column: { 
						width: 100,
					},
				},
				role: {
					title: 'Instance Role',
					type: 'input',
					search: { show: false },
					column: { 
						minWidth: 160,
					},
					form:{ show: false },
				},
				characterset: {
					title: '字符集',
					type: 'input',
					search: { show: false },
					column: { 
						minWidth: 160,
					 },
					form: { 
						show: false,
					 },
				},
				encryption: {
					title: '加密方式',
					type: 'input',
					search: { show: false },
					column: { 
						width: 120,
					 },
					form:{
						component:{},
					},
				},
				update_datetime: {
					title: '更新时间',
					type: 'datePicker',
					search: { show: false },
					column: { 
						minWidth: 160,
						sortable: 'custom',
					},
					form:{ show: false },
				},
				superuser: {
					title: 'DBA账户',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				superpwd: {
					title: 'DBA密码',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				}, 
				status: {
					title: '状态',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				online_form: {
					title: '创建单号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				offline_form: {
					title: '移除单号',
					type: 'input',
					search: { show: false },
					column: { show: false },
					form:{
						component:{},
					},
				},
				// 注释编号:django-vue3-admin-crud514816:代码开始行
				// 功能说明:由这个subTable字段来引用相应子表进来
				subTable: {
					title: "账号",
					type: "text",
					form: {
						title: "",  //配置在form内没有title内容
						labelWidth:"0",   //配置子表的宽度占满介面
						component: {
						name: subTableComponent,
						id:compute(({form})=>{
							return form.id
						}),
						on:{
							//可以传进form进去async saveMain({form})
							async saveMain(){
							//保存主表
							const formRef = crudExpose.getFormRef()
							const ret = await formRef.submit()
							//将form改为编辑模式
							let formWrapperRef = crudExpose.getFormWrapperRef();
							// 这个地方要改为拿到ret.res.data，示例中拿到的是ret.res,如果没有拿到值，会出现无法把值传过去窗口，或者传他认为那是一个新的对象
							//如果这里三行代码出现问题，都有可能会导致保存之后，再保存会出现新的对象
							formWrapperRef.setFormData(ret.res.data)
							crudRef.value.formWrapperRef.formOptions.mode = "edit"
							crudRef.value.formWrapperRef.title="编辑"
							}
						}
						},
						col: {
						span: 24
						},
					},
					column: {
						width: 120,
						formatter: ({ row }) => {
						return "限查看或编辑";
						}
					}
				},
				// 注释编号:django-vue3-admin-crud514816:代码结束行
				// 注释编号:django-vue3-admin-crud514816:代码开始行
				// 功能说明:由这个subTable字段来引用相应子表进来
				LinksubTable: {
					title: "DB-Link",
					type: "text",
					form: {
						title: "",  //配置在form内没有title内容
						labelWidth:"0",   //配置子表的宽度占满介面
						component: {
						name: LinksubTableComponent,
						id:compute(({form})=>{
							return form.id
						}),
						on:{
							//可以传进form进去async saveMain({form})
							async saveMain(){
							//保存主表
							const formRef = crudExpose.getFormRef()
							const ret = await formRef.submit()
							//将form改为编辑模式
							let formWrapperRef = crudExpose.getFormWrapperRef();
							// 这个地方要改为拿到ret.res.data，示例中拿到的是ret.res,如果没有拿到值，会出现无法把值传过去窗口，或者传他认为那是一个新的对象
							//如果这里三行代码出现问题，都有可能会导致保存之后，再保存会出现新的对象
							formWrapperRef.setFormData(ret.res.data)
							crudRef.value.formWrapperRef.formOptions.mode = "edit"
							crudRef.value.formWrapperRef.title="编辑"
							}
						}
						},
						col: {
						span: 24
						},
					},
					column: {
						width: 120,
						formatter: ({ row }) => {
						return "限查看或编辑";
						}
					}
				},
				// 注释编号:django-vue3-admin-crud514816:代码结束行
			},
		},
	};
}
